package com.jiyinit.web.core.video.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.jiyinit.web.core.common.config.PropertyPlaceholderConfigurer;
import com.jiyinit.web.core.video.dto.IconUserRequest;
import com.jiyinit.web.core.video.entity.TabCoreIconUserEntity;
import com.jiyinit.web.core.video.enums.IconEnums;
import com.jiyinit.web.core.video.service.IconUserServiceImpl;
import org.apache.poi.poifs.property.Child;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jiyinit.core.framework.base.entity.ResponseDto;
import com.jiyinit.core.framework.base.paging.PagingResult;
import com.jiyinit.core.framework.base.util.Check;
import com.jiyinit.core.framework.base.util.JsonEntityTransform;
import com.jiyinit.web.core.video.dto.IconMainRequest;
import com.jiyinit.web.core.video.entity.TabCoreIconMainEntity;
import com.jiyinit.web.core.video.service.IconMainServiceImpl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

@Controller
@RequestMapping(value = "mobile/iconMain")
public class IconMainController {
	
	private static Logger logger = LoggerFactory.getLogger(IconMainController.class);
	
	@Resource(name = "core.iconMainServiceImpl")
	private IconMainServiceImpl iconMainService;

	@Resource(name = "core.iconUserServiceImpl")
	private IconUserServiceImpl iconUserService;


	/**
	 * 分页查询
	 * @param req
	 * @param request_json
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getPageRows")
	public ResponseEntity<ResponseDto> getPageRows(HttpServletRequest req, String request_json){
        String iconNum = (String) PropertyPlaceholderConfigurer.getContextProperty("INDEX_PAGE_ICON_NUM");
		logger.info("传入参数: {} ,首页显示图标数量: {}", request_json, iconNum);
		IconUserRequest request = JsonEntityTransform.json2Object(request_json, IconUserRequest.class);
		logger.info("转换为obj之后的参数: {}", request.toString());
		request.setLimit(9999);
        //查询该用户拥有的图标
        List<String> iconIds = iconUserService.findIconListByUserId(request.getUserId());
        String[] idArray = iconIds.toArray(new String[iconIds.size()]);

        PagingResult<TabCoreIconUserEntity> pag = iconUserService.findForPage(request);
        List<TabCoreIconUserEntity> rows = pag.getRows();
        if(!Check.isNullCollection(rows)){
            TabCoreIconUserEntity iconUserEntity = rows.get(0);
            String orderNum = iconUserEntity.getOrderNum();
            if(!Check.isNullStr(orderNum)){
                String[] split = orderNum.split(",");
                String[] iconId = removeInvalid(split, idArray);
                if(!Check.isNullObject(iconId)){
                    List<TabCoreIconMainEntity> iconList = iconMainService.findInIds(iconId);
                    convert(iconList);
                    String[] notInIds = removeIdenticalIds(idArray, iconId);
                    List<TabCoreIconMainEntity> noSelected = iconMainService.findInIds(notInIds);
                    iconList.addAll(noSelected);
                    return new ResponseEntity<>(ResponseDto.responseOK(iconList), HttpStatus.OK);
                }
            }
        }

        int maxNum = 0;
        if(Check.isNullObject(idArray)){
            idArray = new String[1];
            idArray[0] = "1";
        }
        if(idArray.length > Integer.valueOf(iconNum)){
            maxNum = Integer.valueOf(iconNum);
        }else{
            maxNum = idArray.length;
        }
        String[] inIds = new String[maxNum];
        for (int i = 0; i < maxNum; i++) {
            inIds[i] = idArray[i];
        }
        List<TabCoreIconMainEntity> iconList = iconMainService.findInIds(inIds);
        convert(iconList);
        if(idArray.length > Integer.valueOf(iconNum)){
            String[] notInIds = new String[idArray.length - Integer.valueOf(iconNum)];
            int j = 0;
            for (int i = Integer.valueOf(iconNum); i < idArray.length; i++) {
                notInIds[j] = idArray[i];
                j++;
            }
            List<TabCoreIconMainEntity> noSelected = iconMainService.findInIds(notInIds);
            iconList.addAll(noSelected);
        }
        return new ResponseEntity<>(ResponseDto.responseOK(iconList), HttpStatus.OK);
	}
    public String[] removeIdenticalIds(String[] main, String[] same){
        ArrayList<String> newArray = new ArrayList<>();
        HashSet<String> str = new HashSet<>();
        str.addAll(Arrays.asList(same));
        for (int i = 0; i < main.length; i++) {
            if(!str.contains(main[i])){
                newArray.add(main[i]);
            }
        }
        return newArray.toArray(new String[newArray.size()]);
    }
    public void convert(List<TabCoreIconMainEntity> iconList){
        for(TabCoreIconMainEntity obj : iconList){
            obj.setIsSelected("1");
        }
    }

    /**
     * 保存图标顺序
     * @param req
     * @param request_json
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/toAdd", method=RequestMethod.POST)
    public ResponseEntity<ResponseDto> saveOrderNum(HttpServletRequest req, String request_json){
        logger.info("传入参数: {}", request_json);
        IconUserRequest request = JsonEntityTransform.json2Object(request_json, IconUserRequest.class);
        TabCoreIconUserEntity iconUserEntity = JsonEntityTransform.json2Object(request_json, TabCoreIconUserEntity.class);
        String orderNum = getOrderNum(request.getIconNames());
        iconUserEntity.setOrderNum(orderNum);
        logger.info("转换为obj之后的参数: {}", request.toString());
        request.setLimit(999);
        PagingResult<TabCoreIconUserEntity> pag = iconUserService.findForPage(request);
        List<TabCoreIconUserEntity> rows = pag.getRows();
        int num = 0;
        if(Check.isNullCollection(rows)){
            num = iconUserService.add(iconUserEntity);
            if(num > 0){
                return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
            }
        }else{
            num = iconUserService.updateByUserId(iconUserEntity);
            if(num > 0){
                return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
            }
        }
        return new ResponseEntity<>(ResponseDto.responseFail("系统异常"),HttpStatus.OK);
    }

    public String getOrderNum(String iconNames){
        String iconNum = (String) PropertyPlaceholderConfigurer.getContextProperty("INDEX_PAGE_ICON_NUM");
        StringBuffer sbf = new StringBuffer();
        String[] split = iconNames.split(",");
        int maxNum = 0;
        if(split.length > Integer.valueOf(iconNum)){
            maxNum = Integer.valueOf(iconNum);
        }else{
            maxNum = split.length;
        }
        for (int i = 0; i < maxNum; i++) {
            String code = IconEnums.getCodeByName(split[i]);
            sbf.append(code+",");
        }
        return sbf.toString();
    }

    public String[] removeInvalid(String[] split, String[] userIcons){
        ArrayList<String> array = new ArrayList<>();
        for (int i = 0; i < split.length; i++) {
            Child:
            for (int j = 0; j < userIcons.length; j++) {
                if(split[i].equals(userIcons[j])){
                    array.add(userIcons[j]);
                    break Child;
                }
            }
        }
        return array.toArray(new String[array.size()]);
    }


}
